package zuoye_3_24;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

//统计任意文件夹中每种文件的个数并打印.
//包含子文件夹.
public class Zuoye2 {
    public static void main(String[] args) {
        String folderPath = "E:\\zhuo_main_fang_zhi"; // 指定文件夹路径
        File folder = new File(folderPath);

        if (folder.exists() && folder.isDirectory()) {
            Map<String, Integer> fileCountMap = new HashMap<>();
            countFiles(folder, fileCountMap);
            printFileCounts(fileCountMap);
        } else {
            System.out.println("指定路径不是有效的文件夹。");
        }
    }

    private static void countFiles(File folder, Map<String, Integer> fileCountMap) {
        for (File file : folder.listFiles()) {
            if (file.isFile()) {
                String extension = getFileExtension(file.getName());
                fileCountMap.put(extension, fileCountMap.getOrDefault(extension, 0) + 1);
            } else if (file.isDirectory()) {
                countFiles(file, fileCountMap); 
            }
        }
    }

    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "unknown" : fileName.substring(dotIndex + 1).toLowerCase();
    }

    private static void printFileCounts(Map<String, Integer> fileCountMap) {
        for (Map.Entry<String, Integer> entry : fileCountMap.entrySet()) {
            System.out.println("文件类型：" + entry.getKey() + "，个数：" + entry.getValue());
        }
    }
}